package main

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/widget"
	"log"
	"strings"
)

var (
	folderPath      binding.String
	outputFile      binding.String
	loading         binding.String
	excludePathsStr binding.String
	excludePaths    []string
)

func init() {
	folderPath = binding.NewString()
	_ = folderPath.Set("未选择")
	outputFile = binding.NewString()
	_ = outputFile.Set("未生成")
	loading = binding.NewString()

	excludePathsStr = binding.NewString()
	_ = excludePathsStr.Set("未设置")
}

func selectFolder(w fyne.Window) fyne.CanvasObject {
	return widget.NewButton("选择文件夹", func() {
		dialog.ShowFolderOpen(func(list fyne.ListableURI, err error) {
			if err != nil {
				dialog.ShowError(err, w)
				return
			}
			if list == nil {
				log.Println("cancel")
				return
			}

			_ = folderPath.Set(list.Path())
			_ = outputFile.Set("未生成")
		}, w)
	})
}

func saveFile(w fyne.Window) fyne.CanvasObject {
	return widget.NewButton("生成树形目录", func() {
		dialog.ShowFileSave(func(writer fyne.URIWriteCloser, err error) {
			if err != nil {
				dialog.ShowError(err, w)
				return
			}
			if writer == nil {
				log.Println("取消")
				return
			}

			doWriteFile(writer, w)
		}, w)
	})
}

// getResultStr 生成文件目录树
func getResultStr() string {
	p, _ := folderPath.Get()
	fn := CreateFNode(p)
	fn.BuildTree()
	return fn.GenerateTreeStr()
}

func doWriteFile(wri fyne.URIWriteCloser, w fyne.Window) {

	_ = outputFile.Set(wri.URI().Path())

	_ = loading.Set("正在生成目录树。。。")

	// 生成并写入结果
	_, _ = wri.Write([]byte(getResultStr()))

	_ = wri.Close()
	_ = loading.Set("")

	dialog.ShowInformation("成功", "树状目录已成功生成", w)
}

func runGui() {
	ap := app.New()

	// 防止中文乱码
	ap.Settings().SetTheme(&MyTheme{})

	w := ap.NewWindow("树状目录生成器")

	sefo := selectFolder(w)
	safi := saveFile(w)

	input := widget.NewEntry()
	input.SetPlaceHolder("输入排除文件，支持模糊匹配，以回车为间隔")
	input.MultiLine = true
	inputContent := container.NewVBox(input, widget.NewButton("确定排除文件", func() {
		excludePaths = strings.Split(input.Text, "\n")
		str := strings.Join(excludePaths, ", ")
		if len(str) > 70 {
			str = str[:70] + "......"
		}
		_ = excludePathsStr.Set(str)
	}))
	inputContent.Resize(fyne.Size{Width: 500, Height: 300})

	content := container.New(
		layout.NewVBoxLayout(),
		container.New(layout.NewHBoxLayout(), widget.NewLabel("当前选择的文件夹："), widget.NewLabelWithData(folderPath)),
		container.New(layout.NewHBoxLayout(), widget.NewLabel("树状目录输出路径："), widget.NewLabelWithData(outputFile)),
		container.New(layout.NewHBoxLayout(), widget.NewLabel("排除文件："), widget.NewLabelWithData(excludePathsStr)),
		inputContent,
		sefo,
		safi,
		widget.NewLabelWithData(loading),
	)

	w.SetContent(content)
	w.Resize(fyne.Size{Width: 700, Height: 600})
	w.ShowAndRun()
}

func main() {
	runGui()
}
